package jhta;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

public class RequestBookUpdate extends JInternalFrame {
	
	MyTableRender render;
	DefaultTableModel model;
	Connection conn;
	RequestBookVo book;
	int serial;
	Vector<Integer> bookVector;
	Vector<RequestBookVo> managerVector = null;
	
	ButtonGroup gubun  = new ButtonGroup(); // 구매여부 구분
	ButtonGroup result = new ButtonGroup(); // 결과 입력 라디오 버튼
	
	
	private JLabel lblNewLabel;
	private JPanel panel;
	private JRadioButton gu2;
	private JRadioButton gu3;
	private JLabel lblNewLabel_2;
	private JTextField findStr;
	private JButton btnNewButton;
	private JPanel panel_1;
	private JScrollPane scrollPane;
	private JTable table;
	private JTextField bookTitle;
	private JTextField bookPublisher;
	private JTextField mid;
	private JLabel label;
	private JLabel label_1;
	private JLabel label_2;
	private JLabel label_3;
	private JLabel lblNewLabel_1;
	private JScrollPane scrollPane_1;
	private JTextArea replNote;
	private JRadioButton gu4;
	private JSeparator separator;
	private JRadioButton re1;
	private JRadioButton re2;
	private JButton btnNewButton_1;
	private JScrollPane scrollPane_2;
	private JTextArea note;
	private JRadioButton gu1;
	private JRadioButton re3;
	private JComboBox comboManager;
	private JLabel lblNewLabel_3;
	private JButton btnNewButton_2;
	private JLabel lblNewLabel_4;
	private JLabel cnt;
	private JLabel lblNewLabel_5;
	private JLabel lblNewLabel_6;
	private JTextField managerName;


	public RequestBookUpdate() {
		super("도서 요청정보 조회 및 수정", true, true, true, true);
		setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);
		setBounds(100, 100, 649, 670);
		
		getContentPane().add(getLblNewLabel(), BorderLayout.NORTH);
		getContentPane().add(getPanel(), BorderLayout.CENTER);
		

	}
	
	public void select(){
		conn = JavaDBConnection.getConn();

		PreparedStatement ps = null;
		ButtonModel bModel = gubun.getSelection();
		String flag = bModel.getActionCommand();
		String find = findStr.getText().trim().toLowerCase();
		bookVector = new Vector<>();
		
		try{
			String sql = "select serial, flag, m.name as irum, mdate, booktitle "
					+ "from request r left outer join  bookmember m "
					+ "on r.mid = m.no "
					+ "where flag like ? and (booktitle like ? or m.name like ? or bookpublisher like ? "
					+ "or note like ? or replnote like ? or managerid like ? )"
					+ " order by serial desc";
			
			ps = conn.prepareStatement(sql);
			ps.setString(1,"%" + flag + "%");
			ps.setString(2, "%" + find + "%");
			ps.setString(3,  "%" + find + "%");
			ps.setString(4,  "%" + find + "%");
			ps.setString(5,  "%" + find + "%");
			ps.setString(6,  "%" + find + "%");
			ps.setString(7,  "%" + find + "%");
			
			ResultSet rs = ps.executeQuery();

			model.setRowCount(0);
			String f="";
			while(rs.next()){
				Vector<String> v = new Vector<>();
				v.add(""+ rs.getInt("serial"));
				
				switch(rs.getString("flag")){
				case "q": f ="요청";break;
				case "p": f ="구매";break;
				case "r": f ="보류";break;
				}
				v.add(f);
				
				v.add(rs.getString("irum"));
				v.add(rs.getString("mdate"));
				v.add(rs.getString("booktitle"));
				
				model.addRow(v);
				bookVector.add(rs.getInt("serial"));
			}
			cnt.setText("" + rs.getRow());
			
			
			//관리자만 가져옴.
			sql = "select m.code_no, m.no no , m.name from bookmember m inner join code c "
					+ " on m.code_no = c.code_no where c.code_no=2";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			managerVector = new Vector<>();
			comboManager.removeAllItems();
			
			while(rs.next()){
				RequestBookVo vo =new RequestBookVo();
				vo.setManagerName(rs.getString("name"));
				vo.setSerial(rs.getInt("no"));
				
				System.out.println(rs.getString("name") + "," + rs.getInt("no"));
				
				managerVector.add(vo);
				comboManager.addItem(rs.getString("name"));
			}
			

			rs.close();
			ps.close();
			

		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		
		
	}
	
	public void select(int s) {
		serial = bookVector.get(s);
		conn = JavaDBConnection.getConn();
		PreparedStatement ps = null;

		try {
			String sql = "select r.* , " 
				    + " (select name from request r inner join bookmember m on r.mid = m.no where serial=?) as name1, "
				    + " (select name from request r inner join bookmember m on r.managerid = m.no where serial=?) as name2 " 
				+ " from  request r inner join bookmember m "
				+ " on r.mid = m.no where serial=? ";
			
			ps = conn.prepareStatement(sql);
			ps.setInt(1, serial);
			ps.setInt(2, serial);
			ps.setInt(3, serial);

			ResultSet rs = ps.executeQuery();
			String f = "";
			if (rs.next()) {
				bookTitle.setText(rs.getString("booktitle"));
				bookPublisher.setText(rs.getString("bookpublisher"));
				mid.setText((String) model.getValueAt(table.getSelectedRow(), 2));
				note.setText(rs.getString("note"));
				replNote.setText(rs.getString("replnote"));

				// radio button set
				switch (rs.getString("flag")) {
				case "q":
					re3.setSelected(true);
					break;
				case "p":
					re1.setSelected(true);
					break;
				case "r":
					re2.setSelected(true);
					break;
				}

				managerName.setText(rs.getString("name2"));
				
				// 작업자 id를 사용하여 HashMap에서 이름 가져오기
				comboManager.setSelectedItem(Main.USER_NAME);

			}

			rs.close();
			ps.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void update(){
		String sql = "update request set booktitle=? , bookpublisher =?, note=?, replnote=?, "
				+ " managerid=?,  flag=? where serial = ?";
		
		String f="";
		int no = 0;
		// 현 작업자를 콤보를 기준으로 벡터 조회하기
		for(int i=0 ; i<managerVector.size() ; i++){
			RequestBookVo v = managerVector.get(i);
			if(v.getManagerName().equals(comboManager.getSelectedItem())){
				no = v.getSerial();
				System.out.println("no=" + no);
				break;
			}
		}
		
		
		
		
		try{
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, bookTitle.getText());
			ps.setString(2, bookPublisher.getText());
			ps.setString(3, note.getText());
			ps.setString(4, replNote.getText());
			ps.setInt(5,no);
			
			if(re1.isSelected())       f="p";
			else if (re2.isSelected()) f="r";
			else if (re3.isSelected()) f="q";
			ps.setString(6,f);
			
			ps.setInt(7, serial);
			
			ps.executeUpdate();
			ps.close();
			
			JOptionPane.showMessageDialog(null, "저장이 완료되었습니다.");
			
			
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public void delete(){
		
		int y = JOptionPane.showConfirmDialog(null, "정말 삭제하시겠습니까 ???", 
							"도서요청정보 삭제", JOptionPane.OK_CANCEL_OPTION);
		if(y != JOptionPane.OK_OPTION){
			JOptionPane.showMessageDialog(null, "삭제가 취소되었습니다.");
			return;
		}
		
		
		String sql = "delete from request where serial = ?";
		try{
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setInt(1, serial);
			
			ps.executeUpdate();
			
			ps.close();
					
			select();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			lblNewLabel = new JLabel("도서 요청 결과조회");
			lblNewLabel.setPreferredSize(new Dimension(104, 50));
			lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
			lblNewLabel.setFont(new Font("굴림", Font.PLAIN, 30));
		}
		return lblNewLabel;
	}
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(null);
			panel.add(getLblNewLabel_2());
			panel.add(getFindStr());
			panel.add(getBtnNewButton());
			panel.add(getPanel_1());
			panel.add(getScrollPane());
			panel.add(getBookTitle());
			panel.add(getBookPublisher());
			panel.add(getMid());
			panel.add(getLabel());
			panel.add(getLabel_1());
			panel.add(getLabel_2());
			panel.add(getLabel_3());
			panel.add(getLblNewLabel_1());
			panel.add(getScrollPane_1());
			panel.add(getSeparator());
			panel.add(getRe1());
			panel.add(getRe2());
			panel.add(getBtnNewButton_1());
			panel.add(getScrollPane_2());
			panel.add(getRe3());
			panel.add(getComboManager());
			panel.add(getLblNewLabel_3());
			panel.add(getBtnNewButton_2());
			panel.add(getLblNewLabel_4());
			panel.add(getCnt());
			panel.add(getLblNewLabel_5());
			panel.add(getLblNewLabel_6());
			panel.add(getManagerName());
		}
		return panel;
	}
	private JRadioButton getGu2() {
		if (gu2 == null) {
			gu2 = new JRadioButton("구매된 도서");
			gu2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					select();
				}
			});
			gu2.setActionCommand("p");
			gubun.add(gu2);
		}
		return gu2;
	}
	private JRadioButton getGu3() {
		if (gu3 == null) {
			gu3 = new JRadioButton("미구매 도서");
			gu3.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					select();
				}
			});
			gu3.setActionCommand("q");
			gu3.setSelected(true);
			gubun.add(gu3);
		}
		return gu3;
	}
	private JLabel getLblNewLabel_2() {
		if (lblNewLabel_2 == null) {
			lblNewLabel_2 = new JLabel("요청 도서 조회");
			lblNewLabel_2.setBounds(365, 10, 97, 15);
		}
		return lblNewLabel_2;
	}
	private JTextField getFindStr() {
		if (findStr == null) {
			findStr = new JTextField();
			findStr.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent ke) {
					if(ke.getKeyCode() == KeyEvent.VK_ENTER) select();
				}
			});
			findStr.setBounds(365, 29, 153, 25);
			findStr.setColumns(10);
		}
		return findStr;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("검색");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					select();
				}
			});
			btnNewButton.setBounds(530, 10, 67, 44);
		}
		return btnNewButton;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setBorder(new TitledBorder(null, "\uAD6C\uB9E4 \uAD6C\uBD84", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			panel_1.setBounds(12, 10, 341, 54);
			panel_1.add(getGu1());
			panel_1.add(getGu2());
			panel_1.add(getGu3());
			panel_1.add(getGu4());
		}
		return panel_1;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();

			scrollPane.setBounds(12, 88, 585, 149);
			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JTable getTable() {
		if (table == null) {
			String[] col ={"No","구분","요청자","요청일","도서 제목"};
			model = new DefaultTableModel(col,0);
			
			table = new JTable(model);
			table.addKeyListener(new KeyAdapter() {

				@Override
				public void keyReleased(KeyEvent e) {
					int s = table.getSelectedRow();
					select(s);
				}
			});

			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseReleased(MouseEvent e) {
					int s = table.getSelectedRow();
					select(s);
				}
			});
			char[] c = {'c','c','c','c','l'};
			int[] w ={60,70,100,100,300};
			
			render = new MyTableRender(table, c, w);
		}
		return table;
	}
	private JTextField getBookTitle() {
		if (bookTitle == null) {
			bookTitle = new JTextField();
			bookTitle.setPreferredSize(new Dimension(6, 30));
			bookTitle.setColumns(10);
			bookTitle.setBounds(104, 255, 493, 25);
		}
		return bookTitle;
	}
	private JTextField getBookPublisher() {
		if (bookPublisher == null) {
			bookPublisher = new JTextField();
			bookPublisher.setPreferredSize(new Dimension(6, 30));
			bookPublisher.setColumns(10);
			bookPublisher.setBounds(104, 280, 217, 25);
		}
		return bookPublisher;
	}
	private JTextField getMid() {
		if (mid == null) {
			mid = new JTextField();
			mid.setEditable(false);
			mid.setPreferredSize(new Dimension(6, 30));
			mid.setMinimumSize(new Dimension(6, 25));
			mid.setColumns(10);
			mid.setBounds(104, 303, 116, 25);
		}
		return mid;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("요청 도서명");
			label.setHorizontalAlignment(SwingConstants.RIGHT);
			label.setBounds(12, 258, 80, 15);
		}
		return label;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("출판사");
			label_1.setHorizontalAlignment(SwingConstants.RIGHT);
			label_1.setBounds(12, 283, 80, 15);
		}
		return label_1;
	}
	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("도서 요청자");
			label_2.setHorizontalAlignment(SwingConstants.RIGHT);
			label_2.setBounds(12, 308, 80, 15);
		}
		return label_2;
	}
	private JLabel getLabel_3() {
		if (label_3 == null) {
			label_3 = new JLabel("기타 내용");
			label_3.setHorizontalAlignment(SwingConstants.RIGHT);
			label_3.setBounds(35, 333, 57, 15);
		}
		return label_3;
	}
	private JLabel getLblNewLabel_1() {
		if (lblNewLabel_1 == null) {
			lblNewLabel_1 = new JLabel("결과 입력");
			lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
			lblNewLabel_1.setBounds(35, 422, 57, 15);
		}
		return lblNewLabel_1;
	}
	private JScrollPane getScrollPane_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setBounds(104, 439, 493, 60);
			scrollPane_1.setViewportView(getReplNote());
		}
		return scrollPane_1;
	}
	private JTextArea getReplNote() {
		if (replNote == null) {
			replNote = new JTextArea();
		}
		return replNote;
	}
	private JRadioButton getGu4() {
		if (gu4 == null) {
			gu4 = new JRadioButton("구매 보류");
			gu4.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					select();
				}
			});
			gu4.setActionCommand("r");
			gubun.add(gu4);
		}
		return gu4;
	}
	private JSeparator getSeparator() {
		if (separator == null) {
			separator = new JSeparator();
			separator.setBounds(12, 410, 609, 2);
		}
		return separator;
	}
	private JRadioButton getRe1() {
		if (re1 == null) {
			re1 = new JRadioButton("구매됨");
			re1.setActionCommand("p");
			re1.setBounds(104, 418, 67, 23);
			result.add(re1);
		}
		return re1;
	}
	private JRadioButton getRe2() {
		if (re2 == null) {
			re2 = new JRadioButton("구매 보류");
			re2.setActionCommand("r");
			re2.setBounds(175, 418, 90, 23);
			result.add(re2);
		}
		return re2;
	}
	private JButton getBtnNewButton_1() {
		if (btnNewButton_1 == null) {
			btnNewButton_1 = new JButton("저장");
			btnNewButton_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					update();
					select();
				}
			});
			btnNewButton_1.setBounds(421, 534, 97, 25);
		}
		return btnNewButton_1;
	}
	private JScrollPane getScrollPane_2() {
		if (scrollPane_2 == null) {
			scrollPane_2 = new JScrollPane();
			scrollPane_2.setBounds(104, 338, 493, 60);
			scrollPane_2.setViewportView(getTextArea_2());
		}
		return scrollPane_2;
	}
	private JTextArea getTextArea_2() {
		if (note == null) {
			note = new JTextArea();
		}
		return note;
	}
	private JRadioButton getGu1() {
		if (gu1 == null) {
			gu1 = new JRadioButton("모두");
			gu1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					select();
				}
			});
			gu1.setActionCommand("");
			gubun.add(gu1);
		}
		return gu1;
	}
	private JRadioButton getRe3() {
		if (re3 == null) {
			re3 = new JRadioButton("요청");
			re3.setActionCommand("q");
			re3.setBounds(266, 418, 67, 23);
			result.add(re3);
		}
		return re3;
	}
	private JComboBox getComboManager() {
		if (comboManager == null) {
			comboManager = new JComboBox();
			comboManager.setBounds(279, 534, 139, 25);
		}
		return comboManager;
	}
	private JLabel getLblNewLabel_3() {
		if (lblNewLabel_3 == null) {
			lblNewLabel_3 = new JLabel("현 작업자");
			lblNewLabel_3.setHorizontalAlignment(SwingConstants.RIGHT);
			lblNewLabel_3.setBounds(217, 538, 57, 15);
		}
		return lblNewLabel_3;
	}
	private JButton getBtnNewButton_2() {
		if (btnNewButton_2 == null) {
			btnNewButton_2 = new JButton("삭제");
			btnNewButton_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					delete();
				}
			});
			btnNewButton_2.setBounds(530, 536, 67, 23);
		}
		return btnNewButton_2;
	}
	private JLabel getLblNewLabel_4() {
		if (lblNewLabel_4 == null) {
			lblNewLabel_4 = new JLabel("조회건수 :");
			lblNewLabel_4.setHorizontalAlignment(SwingConstants.RIGHT);
			lblNewLabel_4.setBounds(12, 63, 57, 15);
		}
		return lblNewLabel_4;
	}
	private JLabel getCnt() {
		if (cnt == null) {
			cnt = new JLabel("");
			cnt.setForeground(Color.RED);
			cnt.setFont(new Font("굴림", Font.BOLD, 12));
			cnt.setBounds(81, 63, 57, 15);
		}
		return cnt;
	}
	private JLabel getLblNewLabel_5() {
		if (lblNewLabel_5 == null) {
			lblNewLabel_5 = new JLabel("덧   글");
			lblNewLabel_5.setHorizontalAlignment(SwingConstants.RIGHT);
			lblNewLabel_5.setBounds(35, 444, 57, 15);
		}
		return lblNewLabel_5;
	}
	private JLabel getLblNewLabel_6() {
		if (lblNewLabel_6 == null) {
			lblNewLabel_6 = new JLabel("덧글입력자");
			lblNewLabel_6.setHorizontalAlignment(SwingConstants.RIGHT);
			lblNewLabel_6.setBounds(12, 510, 80, 15);
		}
		return lblNewLabel_6;
	}
	private JTextField getManagerName() {
		if (managerName == null) {
			managerName = new JTextField();
			managerName.setEditable(false);
			managerName.setBounds(104, 507, 116, 25);
			managerName.setColumns(10);
		}
		return managerName;
	}
}
